package com.gwd.task.services.impl;

import com.gwd.task.entity.FileLookupMarkEntity;
import com.gwd.task.entity.map.FileLookUpload;
import com.gwd.task.model.FileLookupMarkDTO;
import com.gwd.task.model.FilesUploadDTO;
import com.gwd.task.repository.FileLookupMarkRepository;
import com.gwd.task.services.FileLookupMarkServer;
import com.gwd.task.services.FilesUploadServer;
import com.gwd.task.services.UserGroupServer;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhiyongming
 * @date 2021/1/27 11:52
 */
@Service
public class FileLookupMarkServerImpl implements FileLookupMarkServer {

    @Resource
    private FileLookupMarkRepository fileLookupMarkRepository;
    @Resource
    private UserGroupServer userGroupServer;
    @Resource
    private FilesUploadServer filesUploadServer;

    @Override
    public List<FileLookupMarkDTO> findByFuIds(List<Long> ids, Long userId) {
        return fileLookupMarkRepository.findByFuIdInAndUserId(ids, userId).stream().map(FileLookupMarkDTO::new).collect(Collectors.toList());
    }

    @Override
    public void save(FilesUploadDTO filesUploadDTO) {
        List<Long> userIds = userGroupServer.findByGroup(filesUploadDTO.getGroupId());
        List<FileLookupMarkEntity> entities = new ArrayList<>();
        userIds.forEach(u -> {
            FileLookupMarkEntity entity = new FileLookupMarkEntity();
            entity.setFuId(filesUploadDTO.getFuId());
            entity.setIsLookUp(0);
            entity.setUserId(u);

            entities.add(entity);
        });

        fileLookupMarkRepository.saveAll(entities);
    }

    @Override
    public void changeState(String fileCode, Long userId) {
        FilesUploadDTO dto = filesUploadServer.findByFileCode(fileCode);
        FileLookupMarkEntity entity = new FileLookupMarkEntity();
        entity.setUserId(userId);
        entity.setFuId(dto.getFuId());
        fileLookupMarkRepository.findOne(Example.of(entity)).ifPresent(e->{
            e.setIsLookUp(1);
            fileLookupMarkRepository.save(e);
        });
    }
}
